package com.me.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.print.attribute.HashAttributeSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;

import com.me.bean.JsonDateStructure;
import com.me.entity.NewsRecords;
import com.me.util.GetTIme;

@Service
public class SingleChatMsgDataService {

	@Autowired
	FriendService friendService;
	@Autowired
	private UserInfoService uis;
	@Autowired
	private WebSocketHandler ws;
	@Autowired
	private SingleCharMsgService singleCharMsgService;
	@Transactional
	public void init(String msg, String receiver, String sender) {
		int senderId = uis.getUserIdByAccount(sender);
		int receiverId = uis.getUserIdByAccount(receiver);
		Date time = GetTIme.getNowTime();
		
		List list=friendService.getFriendsEntityBytwo(senderId, receiverId);
		
		if(list.size()==0 || list.isEmpty()){
			System.out.println("不存在好友关系");
			return;
		}
		NewsRecords nr=new NewsRecords();
		nr.setCtime(time);
		nr.setContent(msg);
		nr.setIsread(0);
		nr.setRuid(receiverId);
		nr.setSuid(senderId);
		nr.setType("text");
		System.out.println("------实体对象:newsrecords：构建完成");
		singleCharMsgService.save(nr);
		
		System.out.println("singlechatmsgserver------>id:"+nr.getId());
		String msg_="{\"msg_id\":\""+nr.getId()+"\",\"msg\":\""+msg+"\"}";
		JsonDateStructure jds = new JsonDateStructure();
		jds.setDatetype("json");
		jds.setMsgcontent(msg_);
		jds.setResptype("singlechat");
		jds.setReceiver(receiver);
		jds.setSender(sender);
		jds.setDate(time);
		
		System.out.println("------响应数据：构建完成");
		if (WebSocketHandler.isOnline(receiver)) {
			// 构建转发数据
			System.out.println("------用户在线");
			
			System.out.println("------数据保存完毕");
			

			String respMsg_toreceiver = jds.toJson();
			Map<String,TextMessage> se=new HashMap<>();
			se.put(receiver, new TextMessage(respMsg_toreceiver));
			
			String respMsg_tosender = jds.toJson();
			se.put(sender, new TextMessage(respMsg_toreceiver));
			
			ws.sendMsgToUsers(se);
			
			
			
			
		}else{
			jds.setReceiver(receiver);
			String respMsg_tosender = jds.toJson();
			ws.sendMsgToUser(sender, new TextMessage(respMsg_tosender));
		}
	}

}
